const express = require("express");
const bodyParser = require('body-parser');
const multer  = require('multer');
const apicache = require("apicache");
const path = require("path");
const fs = require("fs");
const app = express();
var server = require('http').createServer(app);
const result = require('./utils/result')
const io = require('socket.io')(server);
const InsertMsg = require('./utils/insertChat');
let cache = apicache.middleware;

app.use(bodyParser.json({limit: '5mb'}));
app.use(bodyParser.urlencoded({ extended: false }));
const upload = multer({ dest: './public/upload' });
// 跨域设置
app.all("*", function(req, res, next) {
  if (req.path !== "/" && !req.path.includes(".")){
    res.header("Access-Control-Allow-Credentials", true);
    // 这里获取 origin 请求头 而不是用 *
    res.header("Access-Control-Allow-Origin", req.headers["origin"] || "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With,Content-Type");
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    res.header("Content-Type", "application/json;charset=utf-8");
  }
  next();
});
// const onlyStatus200 = (req, res) => res.statusCode === 200;
// app.use(cache("30 second", onlyStatus200));
const Wrap = fn=>(req,res)=>{fn(req,res)};

fs.readdirSync("./router/").forEach(file=>{
  if(/\.js$/i.test(file) === false){
    return;
  }
  let route;
  route = '/'+file.replace(/\.js$/i, "")
  .replace(/_/g, "/")
  .replace(/[A-Z]/g, a => {
    return "/" + a.toLowerCase();
  });
  app.use(route,Wrap(require("./router/"+file)))
})
app.post('/upload-single',upload.single('image'), function(req, res, next) {
  console.log(req.body);
  console.log(req.file);
  let file = Date.parse(new Date())+Math.random().toString(36).substr(2,5).toUpperCase()+'.'+req.file.originalname.split('.').reverse()[0]
  // console.log(file)
  fs.renameSync(req.file.path,req.file.destination+'/'+file);
  res.send(new result(200,{data:file},'ok'))
});
app.use(express.static(path.resolve(__dirname, "public")));
server.listen(
2333 , () => {
        console.log(`server running @ http://localhost:${2333}`);
  }
)
var numUsers = 0;
io.on('connection', (socket) => {
  var addedUser = false;
  socket.on('sever red bag',(data)=>{
    let a = data.id;
    socket.emit('red bag'+a,(msg)=>{
    })
  })
  socket.on('sever question',(data)=>{
    let a = data.id;
    socket.emit('question'+a,(msg)=>{

    })
  })
  // when the client emits 'new message', this listens and executes
  socket.on('new message', (data) => {
    let msg = {
      user:socket.username,
      content:data
    };
    InsertMsg(msg)
    // we tell the client to execute 'new message'
    socket.broadcast.emit('new message', {
      username: socket.username,
      message: data
    });
  });

  // when the client emits 'add user', this listens and executes
  socket.on('add user', (username) => {
    if (addedUser) return;

    // we store the username in the socket session for this client
    socket.username = username;
    ++numUsers;
    addedUser = true;
    socket.emit('login', {
      numUsers: numUsers
    });
    // echo globally (all clients) that a person has connected
    socket.broadcast.emit('user joined', {
      username: socket.username,
      numUsers: numUsers
    });
  });

  // when the client emits 'typing', we broadcast it to others
  socket.on('typing', () => {
    socket.broadcast.emit('typing', {
      username: socket.username
    });
  });

  // when the client emits 'stop typing', we broadcast it to others
  socket.on('stop typing', () => {
    socket.broadcast.emit('stop typing', {
      username: socket.username
    });
  });

  // when the user disconnects.. perform this
  socket.on('disconnect', () => {
    if (addedUser) {
      --numUsers;

      // echo globally that this client has left
      socket.broadcast.emit('user left', {
        username: socket.username,
        numUsers: numUsers
      });
    }
  });
});